package com.junlong0716.enjoylearning.ui

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.JsonArray
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ContactAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.SortModel
import com.junlong0716.enjoylearning.entity.SortToken
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.parser.CharacterParser
import com.junlong0716.enjoylearning.parser.PinyinComparator
import com.junlong0716.enjoylearning.utils.ConvertUtils
import com.junlong0716.enjoylearning.widget.SideBar
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_contact.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

class ContactActivity : AppCompatActivity(), BaseQuickAdapter.RequestLoadMoreListener {

    private lateinit var contactAdapter: ContactAdapter
    private lateinit var contactList: ArrayList<SortModel>
    private var currentPage = 1
    private var pageSize = 1000
    private var isLoadingMore = false
    private lateinit var selectedContact: ArrayList<Int>
    private var knowledgeId = 0

    /** 汉字转换成拼音的类  */
    private var characterParser: CharacterParser? = null

    /** 根据拼音来排列ListView里面的数据类  */
    private var pinyinComparator: PinyinComparator? = null


    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contact)
        tv_title.text = "选择联系人"
        rl_back.setOnClickListener { finish() }

        knowledgeId = intent.getIntExtra("KNOWLEDGE_ID", 0)

        contactList = ArrayList()

        /** 给ListView设置adapter **/
        characterParser = CharacterParser.instance
        pinyinComparator = PinyinComparator()


        contactAdapter = ContactAdapter(contactList, R.layout.item_contact)
        rv_list.layoutManager = LinearLayoutManager(this)
        rv_list.adapter = contactAdapter
        rv_list.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST))
        contactAdapter.setOnLoadMoreListener(this, rv_list)
        contactAdapter.setOnItemClickListener { adapter, view, position ->
            //            contactList[position].isChecked = !contactList[position].isChecked
//            contactAdapter.notifyItemChanged(position)
//            selectedContact = ArrayList()
//            for (i in 0 until contactList.size) {
//                if (contactList[i].isChecked) {
//                    selectedContact.add(contactList[i].contactId)
//                }
//            }
//            bt_share.text = "分享（${selectedContact.size}）"


        }

        contactAdapter.setOnItemClickListener { adapter, view, position ->
            contactAdapter.toggleChecked(position)
//            val viewHolder = view.tag as c
//            viewHolder.getCbChecked().performClick()
//            adapter.toggleChecked(position)
            contactAdapter.notifyItemChanged(position)


            val selectList = contactAdapter.getSelectList()

            if (selectList.isEmpty()) {
                bt_share.text = "分享"
            } else
                bt_share.text = "分享（${selectList.size}）"
        }

        requestContactList()

        bt_clear.setOnClickListener {
            //            for (i in 0 until contactList.size) {
//                contactList[i].isChecked = false
//            }
//            contactAdapter.notifyDataSetChanged()
//            bt_share.text = "分享"
            contactAdapter.clearSelected()
            contactAdapter.notifyDataSetChanged()

            if (contactAdapter.getSelectList().isEmpty()) {
                bt_share.text = "分享"
            }
        }

        sliderBar.setTextView(showIndex)


        /**清除输入字符**/
        ivClearText.setOnClickListener {
            et_search.setText("")
        }

        et_search.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}

            override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {
            }

            override fun afterTextChanged(e: Editable) {
                val content = et_search.text.toString()
                val isEquals = "" == content
                ivClearText.visibility = if (isEquals) View.INVISIBLE else View.VISIBLE
                if (content.isNotEmpty()) {
                    val fileterList = ConvertUtils.search(content, contactList) as java.util.ArrayList<SortModel>
                    contactAdapter.updateListView(fileterList)
                    //mAdapter.updateData(mContacts);
                } else {
                    contactAdapter.updateListView(contactList)
                }
                rv_list.scrollToPosition(0)
            }
        })

        sliderBar.setOnTouchingLetterChangedListener(object : SideBar.OnTouchingLetterChangedListener {
            override fun onTouchingLetterChanged(s: String) {
                //该字母首次出现的位置
                val position = contactAdapter.getPositionForSection(s[0].toInt())
                if (position != -1) {
                    rv_list.scrollToPosition(position)
                }
            }
        })

        bt_share.setOnClickListener {
            val selectList = contactAdapter.getSelectList()
            if (selectList.isEmpty()) {
                ToastUtils.showShort("请选择分享联系人！")
                return@setOnClickListener
            }
            val userIdArray = ArrayList<Int>()
            for (i in 0 until selectList.size) {
                userIdArray.add(selectList[i].userId)
            }

            val map = HashMap<String, Any>()
            map["userId"] = MyApp.instance().userAccount!!.id
            map["knowledgeId"] = knowledgeId
            map["shareIds"] = userIdArray
            OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_SHARE_KNOWLEDGE)
                    .tag(this)
                    .upJson(JSONObject(map))
                    .execute(object :StringCallback(){
                        override fun onSuccess(response: Response<String>?) {
                            val jsonObject = JSONObject(response!!.body())
                            val code = jsonObject.getString("code")
                            if (code == "200"){
                                ToastUtils.showShort("分享成功！")
                                finish()
                            }
                        }

                        override fun onError(response: Response<String>?) {
                            ToastUtils.showShort("分享失败！请检查网络！")
                        }
                    })
        }
    }


    private fun requestContactList() {
        val map = HashMap<String, Int>()
        map["currentPage"] = currentPage
        map["onePageCount"] = pageSize
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_ALL_USER)
                .tag(this)
                .upJson(jsonObject)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .cacheKey("API_ALL_USER")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        if (jsonObj.getString("code") == "200") {
                            val contactData = ArrayList<SortModel>()
                            val jsonArray = jsonObj.getJSONObject("data").getJSONArray("list")
                            for (i in 0 until jsonArray.length()) {
                                val id = jsonArray.getJSONObject(i).getInt("id")
                                val userName = jsonArray.getJSONObject(i).getString("userName")
                                val avatar = jsonArray.getJSONObject(i).getString("headImg")
                                val sortModel = SortModel(id, userName, "", userName, avatar,false)
                                var sortLetters = ConvertUtils.getSortLetterBySortKey(userName, characterParser)

                                if (sortLetters == null) {
                                    sortLetters = ConvertUtils.getSortLetter(userName, characterParser)
                                }

                                sortModel.sortLetters = sortLetters

                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                                    sortModel.sortToken = parseSortKey(userName)
                                else
                                    sortModel.sortToken = ConvertUtils.parseSortKeyLollipop(userName, characterParser)

                                contactData.add(sortModel)

                                Collections.sort(contactData, pinyinComparator)

                                contactAdapter.notifyDataSetChanged()

                            }
                            if (isLoadingMore) {
                                if (contactData.isEmpty()) {
                                    contactAdapter.loadMoreEnd()
                                } else {
                                    contactAdapter.addData(contactData)
                                    contactAdapter.loadMoreComplete()
                                }
                            } else {
                                if (contactData.isEmpty()) {
                                    contactAdapter.emptyView = LayoutInflater.from(this@ContactActivity).inflate(R.layout.view_empty, null)
                                } else {
                                    contactList.addAll(contactData)
                                    contactAdapter.notifyDataSetChanged()
                                }
                            }
                        } else {
                            ToastUtils.showShort("网络请求失败！")
                        }
                    }

                    override fun onCacheSuccess(response: Response<String>?) {
                        val jsonObj = JSONObject(response!!.body())
                        if (jsonObj.getString("code") == "200") {
                            val contactData = ArrayList<SortModel>()
                            val jsonArray = jsonObj.getJSONObject("data").getJSONArray("list")
                            for (i in 0 until jsonArray.length()) {
                                val id = jsonArray.getJSONObject(i).getInt("id")
                                val userName = jsonArray.getJSONObject(i).getString("userName")
                                val avatar = jsonArray.getJSONObject(i).getString("headImg")
                                val sortModel = SortModel(id, userName, "", userName, avatar,false)
                                var sortLetters = ConvertUtils.getSortLetterBySortKey(userName, characterParser)

                                if (sortLetters == null) {
                                    sortLetters = ConvertUtils.getSortLetter(userName, characterParser)
                                }

                                sortModel.sortLetters = sortLetters

                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                                    sortModel.sortToken = parseSortKey(userName)
                                else
                                    sortModel.sortToken = ConvertUtils.parseSortKeyLollipop(userName, characterParser)

                                contactData.add(sortModel)

                                Collections.sort(contactData, pinyinComparator)

                                contactAdapter.notifyDataSetChanged()
                            }
                            if (isLoadingMore) {
                                if (contactData.isEmpty()) {
                                    contactAdapter.loadMoreEnd()
                                } else {
                                    contactAdapter.addData(contactData)
                                }
                            } else {
                                if (contactData.isEmpty()) {
                                    contactAdapter.emptyView = LayoutInflater.from(this@ContactActivity).inflate(R.layout.view_empty, null)
                                } else {
                                    contactList.addAll(contactData)
                                    contactAdapter.notifyDataSetChanged()
                                    onLoadMoreRequested()
                                }
                            }
                        } else {
                            ToastUtils.showShort("网络请求失败！")
                        }
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("网络请求失败！")
                    }
                })
    }


    /**
     * 解析sort_key,封装简拼,全拼
     * @param sortKey
     * @return
     */
    fun parseSortKey(sortKey: String?): SortToken {
        val token = SortToken()
        if (sortKey != null && sortKey.length > 0) {
            //其中包含的中文字符
            val enStrs = sortKey.replace(" ", "").split(ConvertUtils.chReg.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
            var i = 0
            val length = enStrs.size
            while (i < length) {
                if (enStrs[i].length > 0) {
                    //拼接简拼
                    token.simpleSpell = token.simpleSpell + enStrs[i].get(0)
                    token.wholeSpell = token.wholeSpell + enStrs[i]
                }
                i++
            }
        }
        return token
    }

    override fun onLoadMoreRequested() {
        isLoadingMore = true
        ++currentPage
        requestContactList()
    }
}
